<?php
/**
 * Date: 2024.8
 * Author: kahn
 */
namespace service\uc\oauth;

use Log;

class WeixinMicroClient  extends BaseAuthClient
{

    /**
     * //微信小程序登录
     * @param $code
     * @return bool|string
     */

    public function code2session($code){
        $params=array(
            'appid'=>$this->config['appId'],
            'secret'=>$this->config['secret'],
            'js_code'=>$code,
            'grant_type'=>'authorization_code'
        );
        $url='https://api.weixin.qq.com/sns/jscode2session';

        $result=$this->getRequest($url,$params);
        Log::debug("jscode2session code:$code res:", $result);

        return $result;
    }

    /**
     * 微信小程序获取手机号码
     * @param String $code 客户端授权code
     * @param String $mobile
     * @return bool
     */
    public function getPhoneNumber($code, &$mobile): bool
    {
        $tokenParams = array(
            'appid' => $this->config['appId'],
            'secret' => $this->config['secret'],
            'grant_type' => 'client_credential'
        );
        $tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token';
        $res = $this->getRequest($tokenUrl,$tokenParams);
        Log::debug("cgi-bin/token ", $res);
        $info = json_decode($res,true);
        if(!$res || !$info || !isset($info['access_token'])){
            Log::error("小程序获取手机号, 获取access_token失败", $res);
            return false;
        }

        $mobileUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $info['access_token'];
        $mobileRes = $this->postRequest($mobileUrl, json_encode(['code'=>$code]));
        Log::debug("getuserphonenumber ", $mobileRes);
        if(!$mobileRes){
            Log::error("小程序获取手机号, 获取手机号失败", $mobileRes);
            return false;
        }
        $mobileInfo = json_decode($mobileRes,true);
        if(!isset($mobileInfo['phone_info']['phoneNumber']) || $mobileInfo['errcode'] != '0'){
            Log::error("小程序获取手机号, 结果解析失败", $mobileRes);
            return false;
        }
        $mobile = $mobileInfo['phone_info']['phoneNumber'];

        return true;
    }
}